package com.mune.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mune.common.constant.ProductConstant;
import com.mune.common.utils.PageUtils;
import com.mune.common.utils.Query;
import com.mune.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.mune.gulimall.product.dao.AttrDao;
import com.mune.gulimall.product.dao.AttrGroupDao;
import com.mune.gulimall.product.dao.CategoryDao;
import com.mune.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.mune.gulimall.product.entity.AttrEntity;
import com.mune.gulimall.product.entity.AttrGroupEntity;
import com.mune.gulimall.product.entity.CategoryEntity;
import com.mune.gulimall.product.service.AttrService;
import com.mune.gulimall.product.service.CategoryService;
import com.mune.gulimall.product.vo.AttrGroupRelationVo;
import com.mune.gulimall.product.vo.AttrRespVo;
import com.mune.gulimall.product.vo.AttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
  @Autowired
  AttrAttrgroupRelationDao attrAttrGroupRelationDao;
  @Autowired
  AttrGroupDao attrGroupDao;
  @Autowired
  CategoryDao categoryDao;
  @Autowired
  CategoryService categoryService;


  @Override
  public PageUtils queryPage(Map<String, Object> params) {
    IPage<AttrEntity> page = this.page(
            new Query<AttrEntity>().getPage(params),
            new QueryWrapper<AttrEntity>()
    );

    return new PageUtils(page);
  }

  @Transactional
  @Override
  public void saveAttr(AttrVo attr) {
    AttrEntity attrEntity = new AttrEntity();
    // 将vo的数据赋给表对应的Entity对象,进行基本保存
    BeanUtils.copyProperties(attr, attrEntity);
    // 保存基本数据
    this.save(attrEntity);
    // 保存关联关系
    if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() != null) {
      AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
      relationEntity.setAttrGroupId(attr.getAttrGroupId());
      relationEntity.setAttrId(attrEntity.getAttrId());
      attrAttrGroupRelationDao.insert(relationEntity);
    }
  }

  @Override
  public PageUtils queryBaseAttrPage(Map<String, Object> params, Long categoryId, String type) {
    QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", "base".equalsIgnoreCase(type) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
    if (categoryId != 0) {
      queryWrapper.eq("catelog_id", categoryId);
    }
    String key = (String) params.get("key");
    if (!StringUtils.isEmpty(key)) {
      queryWrapper.and((wrapper) -> {
        wrapper.eq("attr_id", key).or().like("attr_name", key);
      });
    }
    IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
    PageUtils pageUtils = new PageUtils(page);
    List<AttrEntity> records = page.getRecords();
    List<AttrRespVo> respVos = records.stream().map((attrEntity) -> {
      AttrRespVo attrRespVo = new AttrRespVo();
      BeanUtils.copyProperties(attrEntity, attrRespVo);

      // 设置分类和分组的名字
      if ("base".equalsIgnoreCase(type)) {
        AttrAttrgroupRelationEntity relationEntity = attrAttrGroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
        if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
          AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
          attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
        }
      }
      CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
      if (categoryEntity != null) {
        attrRespVo.setCatelogName(categoryEntity.getName());
      }
      return attrRespVo;
    }).collect(Collectors.toList());
    pageUtils.setList(respVos);
    return pageUtils;

  }

  @Override
  public AttrRespVo getAttrInfo(Long attrId) {
    AttrRespVo attrRespVo = new AttrRespVo();
    AttrEntity attrEntity = this.getById(attrId);
    BeanUtils.copyProperties(attrEntity, attrRespVo);
    if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
      // 设置分组信息
      AttrAttrgroupRelationEntity attrgroupRelation = attrAttrGroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
      if (attrgroupRelation != null) {
        attrRespVo.setAttrGroupId(attrgroupRelation.getAttrGroupId());
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupRelation.getAttrId());
        if (attrGroupEntity != null) {
          attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
        }
      }
    }
    // 设置分类信息
    Long catelogId = attrEntity.getCatelogId();
    Long[] catelogPath = categoryService.findCatelogPath(catelogId);
    attrRespVo.setCatelogPath(catelogPath);
    CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
    if (categoryEntity != null) {
      attrRespVo.setCatelogName(categoryEntity.getName());
    }
    return attrRespVo;
  }

  @Transactional
  @Override
  public void updateAttr(AttrVo attr) {
    AttrEntity attrEntity = new AttrEntity();
    BeanUtils.copyProperties(attr, attrEntity);
    this.updateById(attrEntity);
    // 修改分组关联
    if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
      AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
      relationEntity.setAttrGroupId(attr.getAttrGroupId());
      relationEntity.setAttrId(attr.getAttrId());

      Integer count = attrAttrGroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
      if (count > 0) {
        attrAttrGroupRelationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
      } else {
        attrAttrGroupRelationDao.insert(relationEntity);
      }
    }
  }

  /**
   * 根据分组id查找关联的所有基本属性
   *
   * @param attrGroupId
   * @return
   */
  @Override
  public List<AttrEntity> getRelationAttr(Long attrGroupId) {
    List<AttrAttrgroupRelationEntity> entityList = attrAttrGroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
    if (entityList.isEmpty()) return null;
    List<Long> attrIds = entityList.stream().map(attr -> attr.getAttrId()).collect(Collectors.toList());
    if (attrIds == null || attrIds.size() == 0) return null;
    Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
    return (List<AttrEntity>) attrEntities;
  }

  @Override
  public void deleteRelation(AttrGroupRelationVo[] vos) {
//        attrAttrGroupRelationDao.delete(new QueryWrapper<>(.eq("attr_id",1L).eq("attr_group_id",1L)));
    List<AttrAttrgroupRelationEntity> entities = Arrays.asList(vos).stream().map(item -> {
      AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
      BeanUtils.copyProperties(item, relationEntity);
      return relationEntity;
    }).collect(Collectors.toList());
    attrAttrGroupRelationDao.deleteBatchRelation(entities);
  }

  /**
   * 获取当前分组没有关联的所有属性
   *
   * @param attrGroupId
   * @param params
   * @return
   */
  @Override
  public PageUtils getNoRelationAttr(Long attrGroupId, Map<String, Object> params) {
    // 根据attrGroupId查询出当前分组实例
    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
    // 获取当前分组所在分类
    Long catelogId = attrGroupEntity.getCatelogId();
    // 查询出该分类下所有分组
    List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
    // 获取到该分类下所有分组的组id
    List<Long> collect = group.stream().map(item -> item.getAttrGroupId()).collect(Collectors.toList());
    // 查询出这些分组实例
    List<AttrAttrgroupRelationEntity> groupId = attrAttrGroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));
    // 将分组实例关联的属性id获取出来
    List<Long> attrIds = groupId.stream().map(item -> item.getAttrId()).collect(Collectors.toList());
    QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
    // 排除己被关联的属性
    if (attrIds.size() > 0) {
      queryWrapper.notIn("attr_id", attrIds);
    }
    // 模糊查询
    String key = (String) params.get("key");
    if (!StringUtils.isEmpty(key)) {
      queryWrapper.and(w -> w.eq("attr_id", key).or().like("attr_name", key));
    }
    IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
    return new PageUtils(page);

  }

  @Override
  public List<Long> selectSearchAttrs(List<Long> attrIds) {
    List<Long> attrs = this.baseMapper.selectSearchAttrs(attrIds);
    return attrs;
  }

}